/*
 * @Author: sdorein sdorein@163.com
 * @Date: 2024-08-13 17:43:28
 * @LastEditors: sdorein sdorein@163.com
 * @LastEditTime: 2024-08-15 10:47:50
 * @FilePath: \vite-ts-project\server\index.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

const express = require('express')

const cors = require('cors')
const ci = require('miniprogram-ci');
const { exec } = require('child_process')
// import express from 'express';
// import cors from 'cors';
// import { exec } from 'child_process';
// // 注意：miniprogram-ci 不是一个 ES 模块，所以你需要使用 require 语法来导入它
// const ci = require('miniprogram-ci');
const app = express()
const port = 3000

// 使用cors中间件
app.use(cors())
// 构建接口
app.post('/build', (req, res) => {
  exec('npm run build:mp', (error, stdout, stderr)=> {
    if (error) {
      console.error(`执行错误: ${error}`)
      return res.status(500).send(`执行错误: ${error}`)
    }
    console.log(`stdout: ${stdout}`)
    console.error(`stderr: ${stderr}`)
    res.send('打包成功')
  })
})

// 上传接口
app.post('/upload', async (req, res) => {
  try {
    const project = new ci.Project({
      appid: 'wx70a595fc42f347f0',
      type: 'miniProgram',
      projectPath: './dist/mp-weixin',
      privateKeyPath: './private/private.wx70a595fc42f347f0.key',
      ignores: ['node_modules/**/*'],
    })
    await ci.upload({
      project,
      version: '1.1.5',
      desc: 'hello',
      setting: {
        es6: true,
      }
    });

    res.send('Upload successful');
  } catch (error) {
    res.status(500).send('Error uploading: ' + error.message);
  }
});
app.listen(port, () => {
  console.log(`服务器运行在 http://localhost:${port}`);
})